import sys
import os

import joblib
import numpy as np
import pandas as pd
from flask import Flask, jsonify, request
from flask_cors import CORS

app = Flask(__name__)
CORS(app)


def resource_path(relative_path):
    if getattr(sys, "frozen", False):
        base_path = sys._MEIPASS
    else:
        base_path = os.path.abspath('.')
    return os.path.join(base_path, relative_path)


model_path = resource_path('save_model')
model_params = joblib.load(os.path.join(model_path, 'model.joblib'))
print(model_params)
model = model_params['model']
params = model_params['feature']


def get_prediction(file):
    try:
        data = pd.DataFrame([file])
        x_input = data[params]
        x_input = np.array(x_input)
        y_predict = model.predict(x_input)
        y_predict = np.float64(y_predict[0])
        res = {"predict": y_predict}
        
        return_info = {'data': res, 'message': 'Prediction Success', 'status': 200}
    except Exception as e:
        return_info = {'data': {'predict': None}, 'message': {'error': str(e)}, 'status': 400}
    return return_info


@app.route('/predict', methods=['POST'])
def predict():
    file = request.get_json()
    info = get_prediction(file)
    return jsonify(info)


if __name__ == '__main__':
    app.run(host="0.0.0.0", port=5090, debug=False)